<template>
  <div>
    <el-form @submit.native.prevent class="query-table-form" :inline="true" :model="params">
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="担保客户查询"
          clearable
          @change="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-plus" @click="handleEdit()">新增</el-button>
      </el-form-item>
    </el-form>

    <c-table border v-loading="loading" class="table-sm" :columns="tableColumns" :data="tableData">
      <template v-slot:tags="scope">
        <el-popover placement="top-start" title="附件状态" trigger="hover">
          <div v-for="(tag, index) in scope.row.tags" :key="index">
            <div>
              <i class="fa fa-fw mr-1" :class="tag.icon"></i>
              <span>{{ tag.tag }}</span>
            </div>
          </div>
          <span slot="reference" class="badge" :class="`badge-${scope.row.tagStyle}`">
            {{ scope.row.tagLabel }}
          </span>
        </el-popover>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <project-new-dialog
      :visible.sync="editVisible"
      :table-id="tableId"
      :form-data="formData"
      @success="getData()"
    ></project-new-dialog>

    <attach-dialog
      :visible.sync="attachVisible"
      :project-data="attachData"
      update-attach-status
      @after-data="handleUploadSuccess"
    ></attach-dialog>

    <project-view-dialog
      :visible.sync="viewVisible"
      :batch-no="viewAttachNo"
      :tab-name="viewTabName"
      :query-id="queryId"
    ></project-view-dialog>
  </div>
</template>

<script>
import ProjectNewDialog from '@/bank/views/fast/new/ProjectNewDialog'
import AttachDialog from '@/bank/views/fast/AttachDialog'
import ProjectViewDialog from '@/bank/views/fast/ProjectViewDialog'

import { fastParams, projectIsCompany } from '@/bank/views/fast/index'
import { enumPersonalTags, enumCompanyTags } from '@/bank/views/fast/attach'

export default {
  components: {
    ProjectNewDialog,
    AttachDialog,
    ProjectViewDialog,
  },
  mixins: [fastParams],
  data() {
    return {
      batchKey: 'customer_related_quick_batch_id',
      loading: false,
      order: {
        create_time: 'desc',
      },
      params: {
        index: 1,
        size: 10,
        'channel_claim_status.eq': 1,
      },
      enumAttachmetStatus: {
        0: '未完成',
        1: '已完成',
      },
      tableName: 'customer_related_quick',
      tableData: [],
      tableColumns: [
        { attrs: { label: '借款人', prop: 'customer_name', width: 100 } },
        { attrs: { label: '组织类型', prop: 'org_class_name' } },
        { attrs: { label: '证件号', prop: 'customerNo', width: 120 } },
        { attrs: { label: '授信金额', prop: 'apply_funds' } },
        { attrs: { label: '资金用途', prop: 'funds_use_dir', width: 120 } },
        { attrs: { label: '本次支用金额', prop: 'cur_use_funds' } },
        { attrs: { label: '贷款(支用)期限', prop: 'months' } },
        { attrs: { label: '贷款利率', prop: 'load_rate' } },
        { attrs: { label: '担保费率', prop: 'gua_rate' } },
        { attrs: { label: '保费金额(元)', prop: 'gua_fee' } },
        { attrs: { label: '贷款开始时间', prop: 'load_date', width: 100 } },
        { attrs: { label: '贷款结束时间', prop: 'load_end_date', width: 100 } },
        { attrs: { label: '添加日期', prop: 'createTime', width: 90 } },
        { attrs: { label: '附件状态', align: 'center' }, slot: 'tags' },
        {
          attrs: { label: '操作', align: 'center', width: 100, fixed: 'right' },
          operations: [
            {
              content: '资料要件',
              icon: 'fa fa-edit',
              event: this.handleAttach,
              attrs: { class: 'p-0 m-2' },
            },
            {
              content: '查看',
              icon: 'fa fa-search',
              event: this.handleView,
              attrs: { class: 'p-0 m-2' },
            },
            // { content: '修改', icon: 'fa fa-edit', event: this.handleEdit, attrs: { class: 'p-0 m-2' } }
          ],
        },
      ],
      totalCount: 0,
      editVisible: false,
      tableId: '',
      formData: {},
      viewVisible: false,
      queryId: '',
      attachVisible: false,
      attachData: {},
      viewTabName: 'detail',
      viewAttachNo: '',
    }
  },

  created() {},
  computed: {
    status() {
      return this.$route.query.status
    },
  },
  watch: {
    status: {
      handler: function (val) {
        this.params = { ...this.params, ...this.baseParams }
        this.params['datum_status.eq'] = +val === 1 ? 0 : ''
        this.getData()
      },
      immediate: true,
    },
  },
  methods: {
    handleAttach(row = {}) {
      this.attachData = { ...row }
      this.attachVisible = true
    },
    handleView(row = {}) {
      this.queryId = row.customer_related_id || ''
      this.viewAttachNo = row[this.batchKey]
      this.viewTabName = 'detail'
      this.viewVisible = true
    },
    handleEdit(row = {}) {
      this.editVisible = true
      this.tableId = row.customer_related_id || ''
      this.formData = { ...row }
    },
    getData(index = 1) {
      this.loading = true
      this.params.index = index
      this.$api
        .getData(this.$serviceName, this.tableName, this.params, this.order)
        .then(res => {
          const data = res?.data ?? {}
          this.tableData = (data.data || []).map(this.dataAdapter)
          this.totalCount = data.totalCount || 0
          this.getAttach()
        })
        .finally(() => {
          this.loading = false
        })
    },
    dataAdapter(item) {
      item.createTime = this.$utils.dateFormat(item.create_time, 'yyyy-MM-dd hh:mm')
      item.customerNo = +item.customer_type === 1 ? item.register_no : item.lender_idcard
      item.itemStatus = this.enumAttachmetStatus[item.datum_status]
      return item
    },
    getAttach() {
      if (!this.tableData.length) return
      this.loading = true

      Promise.all([
        this.$api.getData(
          this.$serviceName,
          'entrust_contract',
          {
            'customer_related_id.in': this.tableData.map(it => it.customer_related_id).join(','),
          },
          { create_time: 'asc' }
        ),
        this.$api.getData(this.$serviceName, 'datum_customer_attachment', {
          'customer_related_id.in': this.tableData.map(it => it.customer_related_id).join(','),
        }),
        this.$api.getData(
          this.$serviceName,
          'customer_apply_sign',
          {
            'sign_type.eq': 1,
            'customer_related_id.in': this.tableData.map(it => it.customer_related_id).join(','),
          },
          { create_time: 'asc' }
        ),
      ])
        .then(([contractRes, attachRes, singRes]) => {
          const contracts = contractRes.data || []
          const signs = singRes.data || []
          const contractObj = {}
          for (const contract of contracts) {
            const relatedId = contract.customer_related_id
            contractObj[relatedId] = contract
          }
          const signObj = {}
          for (const sign of signs) {
            const relatedId = sign.customer_related_id
            signObj[relatedId] = sign
          }
          const attachs = attachRes.data || []
          const attachObj = {}
          for (const attach of attachs) {
            const relatedId = attach.customer_related_id
            if (!attachObj[relatedId]) {
              attachObj[relatedId] = []
            }
            attachObj[relatedId].push(attach)
          }

          this.tableData = this.tableData.map(it => {
            const isCompany = projectIsCompany(it)
            const relatedId = it.customer_related_id
            const tags = isCompany ? enumCompanyTags : enumPersonalTags
            const atts = attachObj[relatedId] || []
            const contract = contractObj[relatedId] || {}
            let hasFinish = true
            const signData = signObj[relatedId] || {}
            it.tags = tags.map(({ tag, required, slot }) => {
              const hasUpload =
                slot === 'contract' && +(contract.is_online_sign || 2) === 1
                  ? +(contract.customer_sign_approval || 0) !== 0
                  : slot === 'application' && +it.is_online_sign === 1
                  ? +(signData.sign_status || '') === 2
                  : atts.some(att => att.attachment_type === tag)
              if (hasFinish && required && !hasUpload) {
                hasFinish = false
              }

              return {
                tag,
                required,
                hasUpload,
                icon: hasUpload
                  ? 'text-success fa-check'
                  : required
                  ? 'text-danger fa-times'
                  : 'fa-minus',
              }
            })
            it.tagStyle = hasFinish ? 'success' : 'danger'
            it.tagLabel = hasFinish ? '已完成' : '未完成'
            return it
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleUploadSuccess() {
      this.$store.dispatch('getTaskCountSimple', this.productId)
      this.getData(this.params.index)
    },
  },
}
</script>
<style lang="scss" scoped></style>
